package henu.innovation.controller;


import henu.innovation.entity.Exam;
import henu.innovation.entity.Student;
import henu.innovation.entity.Teacher;
import henu.innovation.service.ExamService;
import henu.innovation.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Controller
public class TeacherController {


    @Autowired
    private TeacherService teacherService;

    @Autowired
    private ExamService examService;

    //
    @RequestMapping(value = "teacher_main")
    public ModelAndView teacherMain(){
        ModelAndView model = new ModelAndView();
        model.setViewName("Teacher/teacher_main");
        return model;
   }

    @RequestMapping(value = "teacher_login",method = RequestMethod.POST)
    public ModelAndView teacherSignIn(@RequestParam String name, @RequestParam String password, HttpSession session){
        ModelAndView model = new ModelAndView();
        Teacher teacher = teacherService.TeacherSignIn(name,password);
        System.out.println("到控制层");
        if(null!=teacher){

            model.addObject("msg","登陆成功");
            session.setAttribute("id",teacher.getId());
            session.setAttribute("name",teacher.getName());
            session.setAttribute("fullname",teacher.getFullname());
            int id = (int)session.getAttribute("id");
            System.out.println(id+"登录后测试session");

            model.setViewName("Teacher/teacher_main");
        }else {

            model.addObject("msg","密码或姓名有误！");
            model.setViewName("redirect:/index.jsp");

        }
        return model;
    }
    @RequestMapping(value = "signOut")
    public ModelAndView teacherSignOut(HttpSession session){
        ModelAndView model = new ModelAndView();
        System.out.println("退出");

        session.removeAttribute("id");
        session.removeAttribute("name");
        session.removeAttribute("fullname");
        model.setViewName("redirect:/index.jsp");
        return model;
    }




    @RequestMapping(value = "teacherPasswordChanged",method = RequestMethod.POST)
    public ModelAndView teacherPasswordChanged(ModelAndView mv, @RequestParam String oldpassword, @RequestParam String newpassword1, @RequestParam String newpassword2,HttpSession session) {
        int id = (int)session.getAttribute("id");
        System.out.println(id+"修改口令的session");

        Teacher oldTeacher = teacherService.FindTeacherById(id);
        if(oldpassword.equals(oldTeacher.getPassword())){
            if(newpassword1.equals(newpassword2)) {
                oldTeacher.setPassword(newpassword1);

                if(teacherService.TeacherPasswordChanged(oldTeacher)){
                    System.out.println(id+"口令修改成功的session");
                    System.out.println(oldTeacher.getPassword());

                    mv.addObject("msg","口令修改成功！");
                    return teacherSignOut(session);
                }else {
                    mv.addObject("msg","未知错误，口令未修改成功！");
                }
            }else {mv.addObject("msg","前后两次输入密码不一致！");}
        }else{
            mv.addObject("msg","原密码输入错误！");
        }

        mv.setViewName("Teacher/teacher_main");
        return mv;
    }


    //跳转到考前操作页面
    @RequestMapping(value = "Teacher/teacher_exam_before")
    public ModelAndView teacherExamBefore(HttpSession session){
        ModelAndView mv = new ModelAndView("Teacher/teacher_exam_before");
        mv.addObject("exams",showAllExamsByCreator(session));
        return mv;
    }
    //添加考试
    @RequestMapping(value = "teacher_exam_add")//只有添加考试了才可以看到自己创建的考试，进而编辑，感觉不合理（已改进）
    //@ResponseBody
    public ModelAndView teacherAddExam(ModelAndView model,HttpSession session,@RequestParam String ename,@RequestParam String etime,@RequestParam String eautostart){
        Exam exam = new Exam();
//        etime="2021/6/2 14:30";

        exam.setName(ename);
        exam.setStarttime(etime);
        exam.setAutostart(!eautostart.equals("false"));
        String creator = (String)session.getAttribute("fullname");
        System.out.println(creator);
        exam.setCreator(creator);
        if(teacherService.teacherAddExam(exam)){
            System.out.println(exam);
            System.out.println("添加考试成功");

        }else{
            System.out.println("添加考试失败");
        }
        return teacherExamBefore(session);
    }
    //展示所有考试
//    @RequestMapping(value = "show_all_exams")
    public Map<String,Object> showAllExams(){
        List<Exam> list = teacherService.showAllExams();
        Map<String,Object> map = new HashMap<>();
        map.put("exams",list);
        return map;
    }
//展示老师所有考试
//    @RequestMapping(value = "show_all_exams_bycreator")
    public List<Exam> showAllExamsByCreator(HttpSession session){
        String creator = (String)session.getAttribute("fullname");
        List<Exam> list = teacherService.showAllExamsByCreator(creator);
        return list;
    }

    //删除考试(暂时搞不定了)
    @RequestMapping(value = "teacher_exam_delete")
    public ModelAndView teacherExamDelete(int id,HttpSession session){
        ModelAndView model = new ModelAndView();
        System.out.println("id:"+id);
        teacherService.deleteExamById(id);

        return teacherExamBefore(session);
    }
    //点击编辑跳转到update
    @RequestMapping(value = "teacher_exam_update",method = RequestMethod.GET)
    public ModelAndView teacherExamUpdate(int id){
        ModelAndView model = new ModelAndView();
        model.setViewName("Teacher/teacher_exam_update");
        model.addObject("exam",teacherService.teacherFindExam(id));
        return model;
    }

    /**
     * 编辑 名称、时间、自动开始
     * @param id id
     * @param ename name
     * @param etime time
     * @param eautostart start
     * @return teacher_exam_update
     */
    @RequestMapping(value = "teacher_exam_update",method = RequestMethod.POST)
    public ModelAndView teacherExamUpdate(int id,String ename,String etime,String eautostart){
        Exam exam = teacherService.teacherFindExam(id);
        exam.setName(ename);
        exam.setStarttime(etime);
        //传过来的形式是"false" "false,true"

        exam.setAutostart(!eautostart.equals("false"));
        System.out.println("id:"+id+",ename:"+ename+",etime"+etime+",eautostart:"+eautostart+"---"+!eautostart.equals("false"));

        examService.update(exam);

        ModelAndView model = new ModelAndView();
        model.setViewName("Teacher/teacher_exam_update");
        model.addObject("exam",teacherService.teacherFindExam(id));
        return model;
    }
    //导入学生名单
    @RequestMapping(value = "teacher_student")
    public ModelAndView teacherStudent(@RequestParam(value="filename") MultipartFile file, HttpServletRequest request, HttpServletResponse response){
            if(file==null) return null;
            //获取文件名
            String name=file.getOriginalFilename();
            //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）
            long size=file.getSize();
            if(name==null || ("").equals(name) && size==0) return null;

            //批量导入。参数：文件名，文件。
            boolean b = teacherService.excelUpload(name, file);
            if(b){
                String Msg ="批量导入EXCEL成功！";
                request.getSession().setAttribute("msg",Msg);
            }else{
                String Msg ="批量导入EXCEL失败！";
                request.getSession().setAttribute("msg",Msg);
            }
        ModelAndView model = new ModelAndView();
            model.setViewName("Teacher/teacher_exam_update");
        return model;
        }

    /**
     * 开启按钮
     * @param id exam id
     * @return teacher_main
     */
    @RequestMapping("teacher_exam_begin")
    public ModelAndView begin(int id,HttpSession session){
        Exam exam = teacherService.teacherFindExam(id);
        exam.setStarted(true);
        exam.setUnderway(true);
        examService.update(exam);
        session.setAttribute("examname",exam.getName());
        session.setAttribute("exampaper",exam.getExampaper());
        return teacherMain();
    }

    /**
     * 结束考试
     * @param id exam id
     * @return teacher_exam_after
     */
    @RequestMapping("teacher_exam_stop")
    public ModelAndView stop(int id,HttpSession session){
        //TO DO 还要将学生提交的文件打包,名称用考试名称
        Exam exam = teacherService.teacherFindExam(id);
        exam.setUnderway(false);
        //设置状态
        exam.setFinished(true);
        System.out.println(exam);
        examService.update(exam);

        String uploadPath = session.getServletContext().getRealPath("/WEB-INF/upload");
        uploadPath += "\\" +session.getAttribute("examname");
        File file = new File(uploadPath);
        String[] tempList = file.list();
        List<File> srcFiles = new ArrayList<>();
        if(tempList != null){
            for (String s : tempList) {
                File f = new File(uploadPath + "\\" + s);

                if (f.isDirectory()) {
                    String[] tempList2 = f.list();
                    List<File> srcFiles2 = new ArrayList<>();
                    if (tempList2 != null) {
                        for (int j = 0; j < tempList2.length; j++) {
                            srcFiles2.add(new File(uploadPath + "\\" + s + "\\" + tempList2[j]));
                            System.out.println(tempList2[j] + "正在压缩到" + uploadPath + "\\" + s);
                        }
                    }
                    System.out.println("单个文件压缩路径：" + uploadPath + "\\" + s + ".zip");
                    zipFiles(srcFiles2, new File(uploadPath + "\\" + s + ".zip"));
                } else {
                    srcFiles.add(f);
                }
            }
        }
        System.out.println("总文件路径："+uploadPath+".zip");
        File zipFile = new File(uploadPath + ".zip");
        zipFiles(srcFiles,zipFile);

        session.removeAttribute("examname");
        return teacherExamAfter();
    }

    public void zipFiles(List<File> srcFile, File zipFile){
        byte[] buf=new byte[1024];
        try {
            //ZipOutputStream类：完成文件或文件夹的压缩
            ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFile));
            for (File file : srcFile) {
                FileInputStream in = new FileInputStream(file);
                out.putNextEntry(new ZipEntry(file.getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
            System.out.println("压缩完成.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据id获取要下载的答卷的name
     * @param id examid
     * @return examname
     */
    @ResponseBody
    @RequestMapping(value = "getName",method = RequestMethod.POST)
    public List<String> download(int id){
        Exam exam = teacherService.teacherFindExam(id);
        List<String> list = new ArrayList<>();
        list.add(exam.getName());
        return list;
    }

    //考中
    //学生信息管理
    @RequestMapping("teacher_manage_student")
    public ModelAndView teacherManageStudent(){
        ModelAndView model = new ModelAndView();
        model.setViewName("Teacher/teacher_manage_student");
        return model;
    }
    //考试概况
    @RequestMapping("teacher_manage_summary")
    public ModelAndView teacherManageSummary(){
        ModelAndView model = new ModelAndView();
        model.setViewName("Teacher/teacher_manage_summary");
        return model;
    }
    //教师添加单个学生信息
    @RequestMapping(value = "teacher_add_student",method = RequestMethod.POST)
    public ModelAndView teacherAddStudent(@RequestParam String sno,@RequestParam String sname,@RequestParam String sclass){
        ModelAndView model = new ModelAndView();
        System.out.println(sno+sname+sclass);

        Student newstudent = new Student();
        newstudent.setNumber(sno);
        newstudent.setName(sname);
        newstudent.setClazz(sclass);
        if(teacherService.teacherAddStudent(newstudent)){
            System.out.println(newstudent);
            System.out.println("添加成功");

        }else{
            System.out.println("添加失败");

        }
        model.setViewName("Teacher/teacher_manage_student");
       //
        return model;
    }
    //教师查找学生(无论登不登陆)
    @RequestMapping(value = "teacher_find_student",method = RequestMethod.POST)
    public ModelAndView teacherFindStudent(@RequestParam String isUnlock,@RequestParam String sno, @RequestParam String sname, @RequestParam String sclass){

        ModelAndView mv = new ModelAndView();
        if(null!=teacherService.teacherFindStudent(sno, sname, sclass)){
            mv.addObject("student",teacherService.teacherFindStudent(sno, sname, sclass));
            System.out.println(teacherService.teacherFindStudent(sno, sname, sclass));


        }else{
            mv.addObject("msg","查无此人");
        }


        if (isUnlock.equals("2")){
            mv.setViewName("Teacher/teacher_manage_student");
        }else {
            mv.setViewName("Teacher/teacher_manage_unlock");
        }

        return mv;

    }
    //教师查找学生按ip
    @RequestMapping(value = "teacher_find_student_ip",method = RequestMethod.POST)
    public ModelAndView teacherFindStudentByIp(@RequestParam String ip){
        ModelAndView model = new ModelAndView();
        System.out.println("jinru");

        if(null!=teacherService.teacherFindStudentByIp(ip)){
            model.addObject("student",teacherService.teacherFindStudentByIp(ip));
            System.out.println(teacherService.teacherFindStudentByIp(ip));
        }else{

            model.addObject("msg","查无此人");
        }

        model.setViewName("Teacher/teacher_manage_unlock");
        return model;
    }
    //解除锁定
    @RequestMapping("teacher_manage_unlock")
    public ModelAndView teacherManageUnlock(){
        ModelAndView model = new ModelAndView();

        model.setViewName("Teacher/teacher_manage_unlock");
        return model;
    }

    //通知消息管理
    @RequestMapping("teacher_manage_notify")
    public ModelAndView teacherManageNotify(){
        ModelAndView model = new ModelAndView();
        model.setViewName("Teacher/teacher_manage_notify");
        return model;
    }
    //新增通知
    @RequestMapping(value = "teacher_add_notify",method = RequestMethod.POST)
    public ModelAndView teacherAddNotify(){
        ModelAndView model = new ModelAndView();

        model.setViewName("Teacher/teacher_manage_student");
        return model;
    }
    //展示已登录学生(数据未同步数据库)
    @RequestMapping("teacher_manage_showbind")
    public ModelAndView teacherManageShowBind(){
        ModelAndView model = new ModelAndView();
        model.setViewName("Teacher/teacher_manage_showbind");
        return model;
    }

    //展示未登录学生
    @RequestMapping("teacher_manage_showunbind")
    public ModelAndView teacherManageShowUnbind(){
        ModelAndView model = new ModelAndView();
        model.setViewName("Teacher/teacher_manage_showunbind");
        return model;
    }
    //展示已登录学生中已提交试卷
    @RequestMapping("teacher_manage_showsubmit")
    public ModelAndView teacherManageShowSubmit(){
        ModelAndView model = new ModelAndView();
        model.setViewName("Teacher/teacher_manage_showsubmit");
        return model;
    }
    //展示已登录学生中未提交试卷
    @RequestMapping("teacher_manage_showunsubmit")
    public ModelAndView teacherManageShowUnSubmit(){
        ModelAndView model = new ModelAndView();
        model.setViewName("Teacher/teacher_manage_showunsubmit");
        return model;
    }


    //考后
    @RequestMapping("teacher_exam_after")
    public ModelAndView teacherExamAfter(){
        ModelAndView model = new ModelAndView();
        model.setViewName("Teacher/teacher_exam_after");
        model.addObject("exams",teacherService.showAllExams());
        return model;
    }

    //






}
